var http = require('http');
var express = require('express');
var bodyParser = require('body-parser');
var morgan = require('morgan');
var helper = require('./server/scripts/utils/common');

morgan.token('reqParams', function(req) {
    var params = helper.getParams(req.body);
    // 删除内置参数
    delete params.url;
    delete params.d;
    delete params._local;
    return JSON.stringify(params);
});

morgan.token('nowTime', function(req) {
    return helper.formateDate(new Date(), "yyyy-MM-dd hh:mm:ss");
});

const app = module.exports = express();
// 全局配置
app.set("host", "192.168.18.236");
app.set("port", process.env.PORT || 3000);
app.use("/web", express.static("web"));
// 设置参数解析中间件
//app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.text()); // for parsing text/plain
//app.use(multer()); // for parsing multipart/form-data
// 配置日志
// 无法实现由该日志主动输出response内容，参见https://github.com/expressjs/morgan/issues/32
app.use(morgan(':method :url :status :nowTime - cost :response-time ms - :reqParams'));

// 使用自定义记录日志实现
function bodyLog(req, res, next) {
    // var write = res.write;
    var end = res.end;
    var chunks = [];
    // res.write = function newWrite(chunk) {
    //     chunks.push(chunk);
    //     write.apply(res, arguments);
    // };

    res.end = function newEnd(chunk) {
        if (chunk) {
            chunks.push(chunk);
        }
        end.apply(res, arguments);
    };

    res.once('finish', function logIt() {
        try {
            var body = Buffer.concat(chunks).toString('utf8');
            console.log("response: %s", body);
        } catch (e) {
            console.error(e);
        }
    });

    next();
}
app.use(bodyLog);

// 设置路由
require('./server/scripts/route_config')(app);

http.createServer(app).listen(app.get("port"), app.get("host"), function() {
    var host = app.get("host");
    var port = app.get("port");
    console.log("Example app listening at http://%s:%s", host, port);
});

if (module.hot) {
    module.hot.accept('./server/scripts/route_config', function() {
        require('./server/scripts/route_config')(app);
    });
}
